// ========================================================================
// Copyright 2007-2008 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at 
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//========================================================================

package org.quotidian.jinger_project;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.GenericServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cometd.Bayeux;
import org.cometd.Client;
import org.cometd.Message;
import org.mortbay.cometd.BayeuxService;
import org.mortbay.cometd.ext.AcknowledgedMessagesExtension;
import org.mortbay.cometd.ext.TimesyncExtension;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.log.Log;


public class RedirectServlet extends HttpServlet {

	private String host;
	private String proxyHost;
	private String proxyPort;
	private String encoding;
	private String uri;
	private ServletContext _context;

	public void init() throws ServletException {
		proxyHost = getInitParameter("proxyHost");
		proxyPort = getInitParameter("proxyPort");
		encoding = getInitParameter("encoding");
		//RM uri = getInitParameter("uri");

		_context = this.getServletContext();
		_context.log("Initialized RedirectServlet");
	}

	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String reqUrl = addQuery(req.getRequestURL().toString(), req.getQueryString());
		_context.log("GET: " + reqUrl);

		Hashtable<String, String> hashtable = new Hashtable<String, String>();
		getHeaders(req, hashtable);
		GetPost getpost = new GetPost();
		String errMsg = null;
		
		if (req.getProtocol().startsWith("HTTPS")) {
			errMsg = getpost.doGetSSL(reqUrl, hashtable, encoding, resp);
		} else {
			errMsg = getpost.doGet(reqUrl, hashtable, encoding, resp);
		}
		if (errMsg != null) {
			int i = getpost.getErrorCode();
			if (i > 0)
				resp.sendError(i, errMsg);
			else
				resp.sendError(503, errMsg);
		}
	}

	public void doPost(HttpServletRequest httpservletrequest, HttpServletResponse httpservletresponse) throws ServletException, IOException {
		System.out.println("RedirectServlet.doPost()");
		String string = httpservletrequest.getQueryString();
		String string_3_ = httpservletrequest.getRequestURL().toString();
		Object object = null;
		if (uri != null) {
			uri = normalizeUri(uri);
			String string_4_ = httpservletrequest.getRequestURI();
			if (string_4_ != null) {
				if (!string_4_.startsWith(uri))
					string_4_ = null;
				else if (uri.length() >= string_4_.length())
					string_4_ = null;
				else
					string_4_ = string_4_.substring(uri.length());
				if (string_4_ != null)
					string_3_ = addUri(string_3_, string_4_);
			}
		}
		string_3_ = addQuery(string_3_, string);
		Hashtable<String, String> hashtable = new java.util.Hashtable<String, String>();
		Hashtable hashtable_5_ = new Hashtable();
		Enumeration<String> enumeration = httpservletrequest.getParameterNames();
		while (enumeration.hasMoreElements()) {
			String string_6_ = enumeration.nextElement();
			String[] strings = httpservletrequest.getParameterValues(string_6_);
			if (strings != null && strings.length > 0) {
				for (int i = 0; i < strings.length; i++)
					hashtable_5_.put(string_6_ + "<" + i + ">", strings[i]);
			}
		}
		getHeaders(httpservletrequest, hashtable);
		GetPost getpost = new GetPost();
		String string_7_ = getpost.doAction(httpservletrequest.getMethod().toUpperCase(), string_3_, hashtable_5_, hashtable, -1, proxyHost, proxyPort, encoding, httpservletrequest.getInputStream(), httpservletresponse);
		if (string_7_ != null) {
			int i = getpost.getErrorCode();
			if (i > 0)
				httpservletresponse.sendError(i, string_7_);
			else
				httpservletresponse.sendError(503, string_7_);
		}
	}

	private void getHeaders(javax.servlet.http.HttpServletRequest httpservletrequest, java.util.Hashtable<String, String> hashtable) {
		//System.out.println("RedirectServlet.getHeaders()");
		Enumeration<String> enumeration = httpservletrequest.getHeaderNames();
		while (enumeration.hasMoreElements()) {
			String string = enumeration.nextElement();
			hashtable.put(string, httpservletrequest.getHeader(string));
		}
	}

	private String getHostInfo(String string) {
		//System.out.println("RedirectServlet.getHostInfo()");
		String string_8_ = string;
		int i = string_8_.indexOf("://");
		if (i > 0)
			string_8_ = string_8_.substring(i + 3);
		i = string_8_.indexOf("/");
		if (i > 0)
			string_8_ = string_8_.substring(0, i);
		i = string_8_.indexOf("?");
		if (i > 0)
			string_8_ = string_8_.substring(0, i);
		i = string_8_.indexOf("#");
		if (i > 0)
			string_8_ = string_8_.substring(0, i);
		i = string_8_.indexOf(";");
		if (i > 0)
			string_8_ = string_8_.substring(0, i);
		return string_8_;
	}


	private String addUri(String string, String string_10_) {
		//System.out.println("RedirectServlet.addUri()");
		if (string_10_ == null)
			return string;
		if (string_10_.length() == 0)
			return string;
		if (string_10_.equals("/"))
			return string;
		String string_11_ = string_10_;
		if (string_11_.charAt(0) == '/')
			string_11_ = string_11_.substring(1);
		if (string_11_.length() == 0)
			return string;
		String string_12_ = "";
		String string_13_ = string;
		int i = string_13_.indexOf("?");
		if (i > 0) {
			if (i < string_13_.length() - 1)
				string_12_ = string_13_.substring(i + 1);
			string_13_ = string_13_.substring(0, i);
		}
		if (!string_13_.endsWith("/"))
			string_13_ += "/";
		string_13_ += string_11_;
		if (string_12_.length() > 0)
			string_13_ += "?" + string_12_;
		return string_13_;
	}

	private String normalizeUri(String string) {
		//System.out.println("RedirectServlet.normalizeUri()");
		int i = string.indexOf("*");
		if (i < 0)
			return string;
		if (i == 0)
			return "/";
		return string.substring(0, i);
	}
	
	
/***************************************************************************
 * Utility Functions 
**************************************************************************/

	/**
	 * Appends the query string to the url nicely.
	 */
	private String addQuery(String url, String query) {
		if (query != null) {
			if (url.indexOf("?") < 0)
				return url + "?" + query;
			return url + "&" + query;
		}
		return url;
	}
	
	
}

/*
 * public class RedirectServlet extends HttpServlet { public RedirectServlet() {
 * }
 * 
 * 
 * @Override public void init() throws ServletException {
 * System.out.println("RedirectServlet.init()"); }
 * 
 * 
 * 
 * @Override public void service(HttpServletRequest req, HttpServletResponse
 * res) throws ServletException, IOException {
 * System.out.println("RedirectServlet.service()");
 * 
 * System.out.println(req.getRequestURI());
 * 
 * 
 * 
 * 
 * 
 * while(req.getAttributeNames().hasMoreElements()) {
 * System.out.println(req.getAttributeNames().nextElement()); }
 * 
 * 
 * Map<String,String> pMap = req.getParameterMap(); for (String key :
 * pMap.keySet()) { System.out.println(key + " : " + pMap.get(key)); }
 * 
 * ((HttpServletResponse)res).sendError(503); } }
 */